/* generates pickups every X time */
class PickupSpawner {

	/* initialize */
	constructor(ground, spawn_speed = 60, limit = 5) {

		/* container to keep all pickups with the collectors */
		this.container = ground;

		/* data */
		this.array = [];
		this.limit = limit;
		this.sound = new Audio("audio/crystal_pickup.mp3");
		this.spawn_speed = spawn_speed;

		/* animation to spawn new crystal */
		this.anim_spawn = new Animation(this.spawn_speed);
		this.anim_spawn.start();

	} /* constructor */

	/* update animation, spawn new crystals */
	update() {

		/* update animation */
		if (this.anim_spawn.update()) {

			/* animation stopped */
			if (!this.anim_spawn.is_running()) {

				/* there is space to create new crystal */
				if ( this.array.length < this.limit ) {

					/* create new crystal */
					let crystal = new PIXI.Sprite(
						loader.resources["images/crystal.png"].texture );
					crystal.anchor = {x:0.5, y:0.5};
					crystal.x = crystal.width*2 +Math.floor( Math.random() *(width -crystal.width*4) );
					crystal.y = crystal.height*2 +Math.floor( Math.random() *(height -crystal.height*4) );

					/* add crystal to array */
					this.array.push(crystal);

					/* place crystal in container, based on its bottom Y */
					let position = this.container.children.length;
					let y = crystal.y +crystal.height;
					for (let i = 0; i < this.container.children.length; i++) {
						let child = this.container.children[i];
						let y2 = child.y +child.height;
						if (y < y2) {
							position = i;
							break;
						}
					}
					this.container.addChildAt(crystal, position);

				} /* space to create crystal */

				/* restart animation */
				this.anim_spawn.timer = 0;

			} /* animation stopped */

		} /* animation updated */

	} /* update */

	/* user clicked on a point on the screen,
	 * if they touched a crystal, pick it up and return its index
	 * else return -1
	 */
	collect(p) {

		/* for every crystal */
		for (let i = 0; i < this.array.length; i++) {

			/* user touched crystal */
			if (this.array[i].containsPoint(p)) {

				/* play sound */
				if (!muted) {
					this.sound.play();
				}

				/* return crystal's index */
				return i;

			} /* user touched crystal */

		} /* for every crystal */

		/* no crystal was touched */
		return -1;

	} /* contains */

	/* change speed of spawning crystals */
	set_speed(spd) {
		this.anim_spawn.max = spd;
		this.anim_spawn.timer = 0;
	}

} /* PickupSpawner */
